package zkdemo;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;
import org.apache.curator.framework.recipes.cache.PathChildrenCache.StartMode;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.junit.Before;
import org.junit.Test;

public class Curator_PathChildrenCache {
	CuratorFramework client;
	
	@Before
	public void init() {
		client = CuratorFrameworkFactory.builder()
				.connectString("192.168.10.188:2181")
				.sessionTimeoutMs(5000)
				.connectionTimeoutMs(3000)
				.retryPolicy(new ExponentialBackoffRetry(1000, 3))
				.namespace("zk-book")
				.build();
		client.start();
	}
	
	//事件监听
	@Test
	public void test() throws Exception {
		PathChildrenCache cache = new PathChildrenCache(client, "/pathchildrencache", true);
		cache.start(StartMode.POST_INITIALIZED_EVENT);
		cache.getListenable().addListener(new PathChildrenCacheListener() {
			@Override
			public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
				System.out.println(event.getType()+" : "+event.getData().getPath());
			}
		});
		
		client.create().withMode(CreateMode.PERSISTENT).forPath("/pathchildrencache");
		Thread.sleep(1000);
		client.create().withMode(CreateMode.PERSISTENT).forPath("/pathchildrencache"+"/c1");
		Thread.sleep(1000);
		client.delete().forPath("/pathchildrencache"+"/c1");
		Thread.sleep(1000);
		client.delete().forPath("/pathchildrencache");
		
		Thread.sleep(Long.MAX_VALUE);
		cache.close();
	}
}
